/**
 *
 * jcrt and its source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to obinary.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 Atjava.com Ltd. (http://www.atjava.com) All rights reserved.
 *
 */
package com.atjava.jcrweb.manager;

import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;

import com.atjava.jcrt.JcrtSession;
import com.atjava.jcrt.JcrtSessionFactory;
import com.atjava.jcrt.core.exception.CoreException;
import com.atjava.jcrt.core.query.ConditionData;
import com.atjava.jcrt.core.query.Query;
import com.atjava.jcrweb.JcrWebException;
import com.atjava.jcrweb.info.DirectoryInfo;
import com.atjava.jcrweb.info.LinkInfo;

/**
 * DirectoryManager
 * @author biggie
 *
 */
public class DirectoryManager {

	private static DirectoryManager manager = null;
	private JcrtSessionFactory factory = null;
	private JcrtSession jsession = null;
    /**
     * Log4j
     */
    private Logger log = Logger.getLogger(this.getClass().getName());
    
	public static DirectoryManager getInstance() throws JcrWebException{
		if(manager == null){
			manager = new DirectoryManager();
		}
		return manager;
	}
	
	private DirectoryManager() throws JcrWebException{
		try {
			factory = JcrtSessionFactory.getInstance();
			jsession = factory.openJcrtSession();
		} catch (CoreException e) {
			log.error("DirectoryManager",e);
			throw new JcrWebException(e);
		}
	}
	
	public List<Object> getChildren(String path) throws JcrWebException{
		try {
			return jsession.getChildren(DirectoryInfo.class, path);
		} catch (CoreException e) {
			log.error("getChildren("+path+")",e);
			throw new JcrWebException(e);
		}
	}
	
	public void createDirectory(DirectoryInfo dirInfo,String path) throws  JcrWebException{
		try {
			synchronized(this){
				long id = DataHelper.generatorId(jsession,dirInfo.getClass());
				dirInfo.setId(id);
				Calendar c = Calendar.getInstance();
				c.setTimeInMillis(System.currentTimeMillis());
				dirInfo.setDatetime(c);	
				jsession.save(dirInfo, path+"/"+id);
			}
		} catch (CoreException e) {
			log.error("createDirectory("+dirInfo+","+path+")",e);
			throw new JcrWebException(e);
		} catch (Exception e){
			log.error("createDirectory("+dirInfo+","+path+")",e);
			throw new JcrWebException(e);
		}
	}
	public DirectoryInfo getDirectory(String path) throws  JcrWebException{
		Object obj;
		try {
			obj = jsession.load(DirectoryInfo.class, path);
		} catch (CoreException e) {
			log.error("getDirectory("+path+")",e);
			throw new JcrWebException(e);
		}
		if(obj!=null){
			return (DirectoryInfo)obj;
		}
		return null;
	}
	public void updateDirectory(DirectoryInfo dirInfo,String path) throws  JcrWebException{
		try {
			synchronized(this){
				Calendar c = Calendar.getInstance();
				c.setTimeInMillis(System.currentTimeMillis());
				dirInfo.setDatetime(c);	
				jsession.save(dirInfo, path+"/"+dirInfo.getId());
			}
		} catch (CoreException e) {
			log.error("updateDirectory("+dirInfo+","+path+")",e);
			throw new JcrWebException(e);
		} catch (Exception e){
			log.error("updateDirectory("+dirInfo+","+path+")",e);
			throw new JcrWebException(e);
		}
	}
	public void deleteDirectory(String path,long id) throws  JcrWebException{
		try {
			jsession.delete(DirectoryInfo.class, path+"/"+id);
		} catch (CoreException e) {
			log.error("deleteDirectory("+path+","+id+")",e);
			throw new JcrWebException(e);
		} catch (Exception e){
			log.error("deleteDirectory("+path+","+id+")",e);
			throw new JcrWebException(e);
		}
	}
	public List searchByName(String name) throws JcrWebException{
 		List results = null;
 		try{
 			ConditionData data = new ConditionData();
 			data.setCondition("name", name, ConditionData.CONDITION_CONTAINS);
 			Query query = jsession.createQuery(DirectoryInfo.class, "/", data);
 			results = query.getDefaultResults();
 		}catch(CoreException e){
 			log.error("searchByName("+name+")",e);
 		}catch(Exception e){
 			log.error("searchByName("+name+")",e);
 			throw new JcrWebException(e);
 		}
 	   return results;
	}
	public List searchById(String id) throws JcrWebException{
 		List results = null;
 		try{
 			ConditionData data = new ConditionData();
 			data.setCondition("id", id, ConditionData.CONDITION_EQUAL);
 			Query query = jsession.createQuery(DirectoryInfo.class, "/", data);
 			results = query.getDefaultResults();
 		}catch(CoreException e){
 			log.error("searchById("+id+")",e);
 		}catch(Exception e){
 			log.error("searchById("+id+")",e);
 			throw new JcrWebException(e);
 		}
 	   return results;
	}
	public String getPathName(String path) throws JcrWebException{
		try {
			if((path == null || path.length() == 0) || path == "/"){
				return "/";
			}
			if(path.startsWith("/")){
				path = path.substring(1);
			}
			String[] paths = path.split("/");
			StringBuffer sb = new StringBuffer();
			String med = "";
			for(int i=0;i<paths.length;i++){
				String strPath = "";
				if(i == 0){
					strPath = "/"+paths[i];
				}else{
					strPath = med+"/"+paths[i];
				}
				DirectoryInfo info = (DirectoryInfo)jsession.load(DirectoryInfo.class, strPath);
				if(info != null){
					sb.append("/"+info.getName());
				}
				med = med+"/"+paths[i];
			}
			return sb.toString();
		} catch (CoreException e) {
			log.error("getPathName("+path+")",e);
			throw new JcrWebException(e);
		} catch (Exception e){
			log.error("getPathName("+path+")",e);
			throw new JcrWebException(e);
		}
	}

}
